const express        = require('express');
const router = express.Router();
var request = require('request');

var xlsxj = require("xlsx-to-json");
var multer  = require('multer')
var cors = require('cors');

const fse = require('fs-extra') 
const crypto = require('crypto');    

router.use(cors())

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/util/pdf/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
var upload = multer({ storage: storage });

router.post('/api/uploadXP', upload.fields([{name: 'xlsx'}, {name: 'pdf'}]), 
                fileCheck, parseXLsx, (req, res, next) => {
    //originalname
    //filename
    //path
    var successObj = {code: 0, message: "上传成功", xlsxResult: req.xlsx2json};

    var accPath = '../../public/upload/mailAcc';    //附件集中存放的文件夹
    // var accPath = '/home/wwwroot/www.talenmall.com/public/upload/mailAcc'
    var toPath = `${accPath}/${ genHashTime(req.files.xlsx[0].filename) }`;

    try{
        for(var i=0; i<req.files.pdf.length; i++){

            var oriFilePath = `${req.files.pdf[i].path}`;
            fse.copySync(oriFilePath, `${toPath}/${req.files.pdf[i].filename}`);
        }
        fse.copySync(`${req.files.xlsx[0].path}`, `${toPath}/${req.files.xlsx[0].filename}`);
    }catch(e){
        res.send({code: 500, message: "server err while copying files", e: e})
    }
    reqAPI(req.xlsx2json, toPath)
        .then(resp=>{
            res.send(successObj)
        }, ()=>{
            res.send({code: 500, message: "文件已上传，邮件发送接口请求错误", e: e})
        })


})

function parseXLsx(req, res, next){
    var file = req.files.xlsx[0];
    try{
        xlsxj({
                input: file.path, 
                output: `output/util/xlsx/${new Date().getTime()}_${file.filename}.json`
                }, 
                function(err, result) {
                    if(err) {
                        res.send(err);
                    }else {
                        req.xlsx2json = result;
                        next();
                    }
            });
    }catch(e){
        res.send({code: 500, message: "上传正确格式的XLSX文件！", e: e})
    }
}

function fileCheck(req, res, next){
    if(req.files.pdf.length == 0 || req.files.xlsx.length == 0){
        res.send({code: 1, message: 'upload at least one file!'});
    }else{
        next();
    }
}

function genHashTime(str){
    var ts = new Date().getTime();
    var hash =  crypto.createHmac('sha256', str)
                    .digest('hex').substring(0,16);
    return hash + '_' + ts;
}

function reqAPI(rawData, dir){
    var url = `http://www.talenmall.com/api/mail/p1`;
    var ripeData = encodeURIComponent( JSON.stringify(rawData.data) );
    var ripeDir = encodeURIComponent(dir);
    var toSend = `data=${ripeData}&dir=${ripeDir}`;

    var p = new Promise((resolve, reject)=>{
        request.post({url:url, form: {data: ripeData, dir: ripeDir}}, 
                function(err,httpResponse,body){
                        /* ... */ 
            console.log(body);
            if(err){
                reject();
            }else{
                resolve(body);
            }
                    
        })
    });
    return p;
    
}

module.exports = router;